package Controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import object.CourierObject;
import object.ExpressBranchList;
import object.ExpressList;
import object.HistoryParcel;
import object.UnTakenParcel;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import DAO.AgentDao;
import DAO.BoxDao;
import DAO.BranchDao;
import DAO.CourierDao;
import DAO.ExpressDao;
import DAO.MessageResponseDao;
import DAO.ParcelDao;
import DAO.TerminalDao;
import POJO.Agent;
import POJO.DevList;
import POJO.Parcel;
import Utils.TimeHelper;
import Utils.ValidationHelper;

@Controller
@RequestMapping(value = "parcelService")
public class ParcelServiceController {

	static Logger logger = Logger.getLogger(ParcelServiceController.class);

	static String QUERY_SUCCESS = "00000";// 查询成功
	static String QUERY_FAILURE = "00001";// 查询失败
	static String COMMAND_SUCCESS = "00002";// 命令已接收
	static String COMMAND_FAILURE = "00003";// 命令执行失败
	static String COMMAND_FAILURE_PARCELGETTED = "00004";// 命令执行失败（包裹已被取走）
	static String TIME_OUT = "E0000";// 请求超时
	static String AUTH_ERROR = "E0001";// 身份校验失败
	static String PARAM_ERROR = "E0002";// 参数出错
	static String ABNORMAL_ERROR = "E0009";// 异常（可重新请求）

	private ArrayList<UnTakenParcel> unTakenParcels = null;
	private ArrayList<HistoryParcel> historyParcels = null;

	@Autowired
	BoxDao boxDao;
	@Autowired
	AgentDao agentDao;
	@Autowired
	MessageResponseDao messageResponseDao;
	@Autowired
	TerminalDao terminalDao;
	@Autowired
	BranchDao branchDao;
	@Autowired
	ParcelDao parcelDao;
	@Autowired
	ExpressDao expressDao;
	@Autowired
	CourierDao courierDao;

	/**
	 * 查询代理商快递员信息
	 * 
	 * @param partnerID
	 * @param phone
	 * @param sign
	 * @param t
	 * @return by zgy
	 */
	@RequestMapping("QueryCourierInfo")
	@ResponseBody
	public Map<String, Object> queryCourierInfo(
			@RequestParam("partnerID") String partnerID,
			@RequestParam("courierPhoneNum") String phone,
			@RequestParam("sign") String sign,
			@RequestParam("timestamp") String t) {
		HashMap<String, Object> response = new HashMap<String, Object>();
		CourierObject courier = null;

		try {
			// 检查参数
			long timestamp = Long.parseLong(t);
			long courierPhoneNum = Long.parseLong(phone);
			// 验证请求是否超时
			if (TimeHelper.isNowLate(timestamp, 5)) {
				response.put("responseCode", TIME_OUT);
				response.put("response", "请求已超时");
				return response;
			}
			// varify agent
			Agent agent = agentDao.findByPartnerId(partnerID);
			agent.setTimestamp(timestamp);
			if (agent == null || !agent.varify(sign)) {
				response.put("responseCode", AUTH_ERROR);
				response.put("response", "身份校验失败");
				return response;
			}
			courier = courierDao.queryCourierInfo(agent.getId(),courierPhoneNum);
			if (courier.getExpressCompanyId() == null) {
				response.put("responseCode", QUERY_FAILURE);
				response.put("response", "查询失败(无隶属该代理商的快递员)");
				return response;
			}
		} catch (Exception e) {
			e.printStackTrace();
			response.put("responseCode", PARAM_ERROR);
			response.put("response", "参数错误");
			return response;
		}
		response.put("responseCode", QUERY_SUCCESS);
		response.put("expressCompanyId", courier.getExpressCompanyId());
		response.put("expressBranchId", courier.getExpressBranchId());
		response.put("courierName", courier.getCourierName());
		response.put("courierCardSeq", courier.getCourierCardSeq());
		response.put("courierIDCard", courier.getCourierIDCard());
		response.put("courierAddr", courier.getCourierAddr());
		response.put("response", "查询成功");
		return response;
	}

	/**
	 * 查询代理商快递网点列表
	 * 
	 * @param partnerID
	 * @param companyId
	 * @param sign
	 * @param t
	 * @return by zgy
	 */
	@RequestMapping("QueryExpressBranchList")
	@ResponseBody
	public Map<String, Object> queryExpressBranchList(
			@RequestParam("partnerID") String partnerID,
			@RequestParam("expressCompanyId") String companyId,
			@RequestParam("sign") String sign,
			@RequestParam("timestamp") String t) {
		HashMap<String, Object> response = new HashMap<String, Object>();
		ArrayList<ExpressBranchList> expressBranchLists = null;

		try {
			// 检查参数
			long timestamp = Long.parseLong(t);
			int expressCompanyId = Integer.parseInt(companyId);
			// 验证请求是否超时
			if (TimeHelper.isNowLate(timestamp, 5)) {
				response.put("responseCode", TIME_OUT);
				response.put("response", "请求已超时");
				return response;
			}
			// varify agent
			Agent agent = agentDao.findByPartnerId(partnerID);
			agent.setTimestamp(timestamp);
			if (agent == null || !agent.varify(sign)) {
				response.put("responseCode", AUTH_ERROR);
				response.put("response", "身份校验失败");
				return response;
			}
			expressBranchLists = expressDao.getExpressBranchListByAgentId(
					agent.getId(), expressCompanyId);
			if (expressBranchLists.size() == 0) {
				response.put("responseCode", QUERY_FAILURE);
				response.put("response", "查询失败(无隶属该代理商的快递网点)");
				return response;
			}
		} catch (Exception e) {
			e.printStackTrace();
			response.put("responseCode", PARAM_ERROR);
			response.put("response", "参数错误");
			return response;
		}
		response.put("responseCode", QUERY_SUCCESS);
		response.put("expressCompanyId", companyId);
		response.put("expressBranchList", expressBranchLists);
		response.put("response", "查询成功");
		return response;
	}

	/**
	 * 查询快递总公司列表
	 * 
	 * @param partnerID
	 * @param sign
	 * @param t
	 * @return by zgy
	 */
	@RequestMapping("QueryExpressList")
	@ResponseBody
	public Map<String, Object> queryExpressList(
			@RequestParam("partnerID") String partnerID,
			@RequestParam("sign") String sign,
			@RequestParam("timestamp") String t) {
		HashMap<String, Object> response = new HashMap<String, Object>();
		ArrayList<ExpressList> expressLists = null;

		try {
			// 检查参数
			long timestamp = Long.parseLong(t);
			// 验证请求是否超时
			if (TimeHelper.isNowLate(timestamp, 5)) {
				response.put("responseCode", TIME_OUT);
				response.put("response", "请求已超时");
				return response;
			}
			// varify agent
			Agent agent = agentDao.findByPartnerId(partnerID);
			agent.setTimestamp(timestamp);
			if (agent == null || !agent.varify(sign)) {
				response.put("responseCode", AUTH_ERROR);
				response.put("response", "身份校验失败");
				return response;
			}
			expressLists = expressDao.getExpressListByAgentId(agent.getId());
			if (expressLists.size() == 0) {
				response.put("responseCode", QUERY_FAILURE);
				response.put("response", "查询失败(无隶属该代理商的快递公司)");
				return response;
			}
		} catch (Exception e) {
			e.printStackTrace();
			response.put("responseCode", PARAM_ERROR);
			response.put("response", "参数错误");
			return response;
		}
		response.put("responseCode", QUERY_SUCCESS);
		response.put("expressList", expressLists);
		response.put("response", "查询成功");
		return response;
	}

	/**
	 * 查询设备列表
	 * 
	 * @param partnerID
	 * @param sign
	 * @param timestamp
	 * @return
	 */
	@RequestMapping("QueryDevList")
	@ResponseBody
	public Map<String, Object> queryDevList(
			@RequestParam("partnerID") String partnerID,
			@RequestParam("sign") String sign,
			@RequestParam("timestamp") String t) {
		HashMap<String, Object> response = new HashMap<String, Object>();
		ArrayList<DevList> devLists = null;

		try {
			// 检查参数
			long timestamp = Long.parseLong(t);
			// 验证请求是否超时
			if (TimeHelper.isNowLate(timestamp, 5)) {
				response.put("responseCode", TIME_OUT);
				response.put("response", "请求已超时");
				return response;
			}
			// varify agent
			Agent agent = agentDao.findByPartnerId(partnerID);
			agent.setTimestamp(timestamp);
			if (agent == null || !agent.varify(sign)) {
				response.put("responseCode", AUTH_ERROR);
				response.put("response", "身份校验失败");
				return response;
			}

			devLists = terminalDao.getDevLisByAgentId(agent.getId());
			if (devLists.size() == 0) {
				response.put("responseCode", QUERY_FAILURE);
				response.put("response", "查询失败(无隶属该代理商的设备)");
				return response;
			}
		} catch (Exception e) {
			e.printStackTrace();
			response.put("responseCode", PARAM_ERROR);
			response.put("response", "参数错误");
			return response;
		}
		response.put("responseCode", QUERY_SUCCESS);
		response.put("devList", devLists);
		response.put("response", "查询成功");
		return response;
	}

	/**
	 * 查询包裹信息列表
	 * 
	 * @param partnerID
	 * @param sign
	 * @param userMobileNum
	 * @param parcelNum
	 * @param t
	 * @return
	 */
	@RequestMapping("QueryParcel")
	@ResponseBody
	public Map<String, Object> queryParcel(
			@RequestParam("partnerID") String partnerID,
			@RequestParam("sign") String sign,
			@RequestParam(value = "phoneNum", required = false) String phoneNum,
			@RequestParam(value = "parcelNum", required = false) String parcelNum,
			@RequestParam(value = "role", required = false) String r,
			@RequestParam(value = "status", defaultValue = "-1") String s,
			@RequestParam("timestamp") String t) {
		HashMap<String, Object> response = new HashMap<String, Object>();
		try {
			// 参数检查
			long timestamp = Long.parseLong(t);
			int status = Integer.parseInt(s);
			// 验证请求是否超时
			if (TimeHelper.isNowLate(timestamp, 5)) {
				response.put("responseCode", TIME_OUT);
				response.put("response", "请求已超时");
				return response;
			}
			// varify agent
			Agent agent = agentDao.findByPartnerId(partnerID);
			agent.setTimestamp(timestamp);
			if (agent == null || !agent.varify(sign)) {
				response.put("responseCode", AUTH_ERROR);
				response.put("response", "身份校验失败");
				return response;
			}

			if (phoneNum != null && ValidationHelper.isMobileNum(phoneNum)) {
				int role = Integer.parseInt(r);
				unTakenParcels = parcelDao.queryUnTakenParcelByPhoneNum(
						phoneNum, role, agent.getId(),status);
			} else if (parcelNum != null && !"".equals(parcelNum)) {
				unTakenParcels = parcelDao.queryUnTakenParcelByParcelNum(
						parcelNum, agent.getId(),status);
			} else {
				throw new Exception();
			}

			if (unTakenParcels == null || unTakenParcels.isEmpty()) {
				response.put("responseCode", QUERY_FAILURE);
				response.put("response", "查询失败(系统中没有您的包裹)");
				return response;
			} else {
				response.put("responseCode", QUERY_SUCCESS);
				response.put("parcelList", unTakenParcels);
				response.put("response", "查询成功");
				return response;
			}
		} catch (Exception e) {
			e.printStackTrace();
			response.put("responseCode", PARAM_ERROR);
			response.put("response", "参数错误");
			return response;
		}
	}

	/**
	 * 查询历史包裹列表
	 * 
	 * @param partnerID
	 * @param sign
	 * @param userMobileNum
	 * @param s
	 * @param e
	 * @param t
	 * @return
	 */
	@RequestMapping("QueryHistoryParcel")
	@ResponseBody
	public Map<String, Object> QueryHistoryParcel(
			@RequestParam("partnerID") String partnerID,
			@RequestParam("sign") String sign,
			@RequestParam("phoneNum") String phoneNum,
			@RequestParam("role") String r,
			@RequestParam(value = "startNum", required = false, defaultValue = "0") String s,
			@RequestParam(value = "endNum", required = false, defaultValue = "10") String e,
			@RequestParam("timestamp") String t) {
		HashMap<String, Object> response = new HashMap<String, Object>();
		try {

			// 参数检查
			long timestamp = Long.parseLong(t);
			int role = Integer.parseInt(r);
			int startNum = Integer.parseInt(s);
			int endNum = Integer.parseInt(e);
			int totalNum = 0;

			if (endNum > 20) {
				throw new Exception();
			}

			// 验证请求是否超时
			if (TimeHelper.isNowLate(timestamp, 5)) {
				response.put("responseCode", TIME_OUT);
				response.put("response", "请求已超时");
				return response;
			}
			// varify agent
			Agent agent = agentDao.findByPartnerId(partnerID);
			agent.setTimestamp(timestamp);
			if (agent == null || !agent.varify(sign)) {
				response.put("responseCode", AUTH_ERROR);
				response.put("response", "身份校验失败");
				return response;
			}

			if (phoneNum != null && ValidationHelper.isMobileNum(phoneNum)) {
				historyParcels = parcelDao.queryHistoryParcelByPhoneNum(
						phoneNum, role, agent.getId(), startNum, endNum);
				totalNum = parcelDao.totalHistoryParcels(phoneNum, role,
						agent.getId());
			} else {
				throw new Exception();
			}

			if (historyParcels == null || historyParcels.isEmpty()) {
				response.put("responseCode", QUERY_FAILURE);
				response.put("response", "查询失败(系统中没有您的包裹)");
				return response;
			} else {
				response.put("responseCode", QUERY_SUCCESS);
				response.put("parcelList", historyParcels);
				response.put("totalNum", totalNum);
				response.put("response", "查询成功");
				return response;
			}
		} catch (Exception e1) {
			e1.printStackTrace();
			response.put("responseCode", PARAM_ERROR);
			response.put("response", "参数错误");
			return response;
		}
	}

	
	/**
	 * 强制开锁
	 * @param partnerID
	 * @param sign
	 * @param parcelNum
	 * @param checkCode
	 * @param t
	 * @param effectTime
	 * @return
	 * by zgy
	 */
	@RequestMapping("ForcedOpenBox")
	@ResponseBody
	public Map<String, String> forcedOpenBox(
			@RequestParam("partnerID") String partnerID,
			@RequestParam("sign") String sign,
			@RequestParam("parcelNum") String parcelNum,
			@RequestParam("checkCode") String checkCode,
			@RequestParam("timestamp") String t,
			@RequestParam(value = "cmdEffectiveTime", required = false, defaultValue = "5") String effectTime) {
		HashMap<String, String> response = new HashMap<String, String>();

		try {
			// 检查参数
			long timestamp = Long.parseLong(t);
			// 验证请求是否超时
			if (TimeHelper.isNowLate(timestamp, 5)) {
				response.put("responseCode", TIME_OUT);
				response.put("response", "请求已超时");
				return response;
			}
			// varify agent
			Agent agent = agentDao.findByPartnerId(partnerID);
			// RequestNotifyThread rnt = new RequestNotifyThread();
			agent.setTimestamp(timestamp);
			if (agent == null || !agent.varify(sign)) {
				response.put("responseCode", AUTH_ERROR);
				response.put("response", "身份校验失败");
				return response;
			}
			int cmdEffectiveTime = Integer.parseInt(effectTime);

			Parcel parcel = parcelDao.queryByParcelNum(parcelNum, checkCode,
					agent.getId());

			if (parcel == null) {
				response.put("responseCode", COMMAND_FAILURE);
				response.put("response", "命令执行失败（未找到包裹或包裹已被取走）");
				return response;
			} else if (TimeHelper.isTerminalOff(terminalDao.get(
					parcel.getTerminalId()).getLoginTime())) {
				response.put("responseCode", COMMAND_FAILURE);
				response.put("response", "命令执行失败（设备不在线）");
				return response;
			} else {
				if (boxDao.forceOpenBox(parcel.getTerminalId(),
						Integer.parseInt(parcel.getBoxSeq()), cmdEffectiveTime)
						&& boxDao.updateBoxStatus(parcel.getTerminalId(),
								Integer.parseInt(parcel.getBoxSeq()), 0,null)
						&& parcelDao.updateParcelStatus(parcel.getId(), 5)) {
					response.put("responseCode", COMMAND_SUCCESS);
					response.put("response", "命令已经接收等待执行");
					return response;
				} else {
					response.put("responseCode", ABNORMAL_ERROR);
					response.put("response", "异常（可重新请求）");
					return response;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			response.put("responseCode", PARAM_ERROR);
			response.put("response", "参数错误");
			return response;
		}
	}
}
